<template>
  <div>
    <div>
      <Where
        :queryForm="queryForm"
        :cateGory="cateGory"
        @updateTime="updateTime"
      ></Where>
    </div>

    <Content
      :style="{
        marginTop: '25px',
        boxShadow: '0px 1px 1px 1px rgba(0,0,0,.1)',
        border: 'none',
        borderRadius: '0',
        paddingBottom: '10px',
      }"
    >
      <Row>
        <Table
          ref="table"
          stripe
          :loading="loading"
          v-if="tableData && tableData.length > 0"
          border
          :columns="columns"
          :data="tableData"
        ></Table>
        <Card v-else>
          <div style="text-align: center">
            <h3>没有数据</h3>
          </div>
        </Card>
      </Row>
      <Row :style="{ marginLeft: '15px', marginTop: '15px' }">
        <Page
          v-if="tableData && tableData.length > 0"
          :total="totalCount"
          :page-size="pageSize"
          :current="currentPage"
          show-total
          show-elevator
          show-sizer
          @on-change="setPage"
          @on-page-size-change="setLimit"
        ></Page>
      </Row>
    </Content>
    <Model ref="Model" @query="query"></Model>
  </div>
</template>
<script>
import { mapField } from '@/libs/util.js'
import Config from '@/config'
import Where from './templates/Where.vue'
import Model from './templates/Model.vue'
import moment from 'moment'

export default {
  name: 'Img',
  components: {
    Where,
    Model
  },
  data () {
    let self = this
    return {
      update: false,
      loading: false, // 标示异步请求
      cateGory: [],
      // 查询条件
      queryForm: {
        category_ids: [],
        name: '',
        title: '',
        source_name: '',
        source_path: '',
        status: '',
        create_time_start: moment().format('YYYY-MM-DD') + ' 00:00:00',
        create_time_end: moment().format('YYYY-MM-DD') + ' 23:59:59'
      },
      // 表头
      columns: [
        {
          title: 'ID',
          width: 100,
          align: 'center',
          fixed: 'left',
          key: 'img_id'
        },
        {
          title: '壁纸排序',
          width: 100,
          align: 'center',
          key: 'sort'
        },
        {
          title: '所属类别',
          key: 'category_ids',
          width: 150,
          render: (h, data) => {
            let cateGoryIds = data.row.category_ids.split(',')
            let content = ''
            for (let index = 0; index < cateGoryIds.length; index++) {
              let id = cateGoryIds[index]
              content += this.cateGory[id]['category_name'] + ','
            }
            content = content.substr(0, (content.length - 1))
            return h('div', content)
          }
        },
        {
          title: '壁纸名字',
          key: 'name',
          width: 100
        },
        {
          title: '壁纸标题',
          key: 'title',
          width: 100
        },
        {
          title: '来源名字',
          key: 'source_name',
          width: 100
        },
        {
          title: '来源地址',
          key: 'source_path',
          width: 100
        },
        {
          title: '展示图片',
          key: 'set_path',
          width: 160,
          render: (h, data) => {
            let path = data.row.set_path.split('/')
            let filePath = data.row.set_path.replace(
              path[path.length - 1],
              's_' + path[path.length - 1]
            )
            return h('div', [
              h('img', {
                style: {
                  height: '100px',
                  padding: '5px',
                  verticalAlign: 'middle'
                },
                attrs: {
                  src: Config.imgRootUrl + '/' + filePath
                },
                on: {
                  click: (doc) => {
                    this.$Modal.info({
                      title: '图片详情',
                      width: 800,
                      closable: true,
                      render: (h, d) => {
                        return h(
                          'div',
                          {
                            style: {
                              textAlign: 'center'
                            }
                          },
                          [
                            h('img', {
                              style: {
                                maxWidth: '760px',
                                maxHeight: '540px',
                                padding: '5px',
                                margin: '0px auto'
                              },
                              attrs: {
                                src:
                                  Config.imgRootUrl + '/' + data.row.set_path
                              }
                            })
                          ]
                        )
                      }
                    })
                  }
                }
              })
            ])
          }
        },
        {
          title: '创建时间',
          key: 'create_time',
          align: 'center',
          width: 160
        },
        {
          title: '更新时间',
          align: 'center',
          key: 'update_time',
          width: 160
        },
        {
          title: '状态',
          align: 'center',
          key: 'status',
          width: 100,
          render: (h, data) => {
            return h('div', [
              h('i-switch', {
                props: {
                  type: 'primary',
                  size: 'large',
                  value: data.row.status == 1 // 控制开关的打开或关闭状态，官网文档属性是value
                },
                scopedSlots: {
                  open: function () {
                    return h('span', '启动')
                  },
                  close: function () {
                    return h('span', '禁用')
                  }
                },
                on: {
                  'on-change': async (value) => {
                    // 触发事件是on-change,用双引号括起来，
                    data.row.status = value === true ? 1 : 2
                    // 参数value是回调值，并没有使用到
                    let param = {
                      img_id: data.row.img_id,
                      status: value === true ? 1 : 2
                    }
                    let result = await self.post(
                      `/admin/Img/imgStatusUpdate`,
                      param
                    )
                    if (result.data.code != 200) {
                      data.row.status = value === true ? 2 : 1
                      self.$Message.error(result.data.msg)
                    } else {
                      // 还原开关
                      self.$Message.success(result.data.msg)
                    }
                  }
                }
              })
            ])
          }
        },
        {
          title: '备注',
          align: 'center',
          key: 'remark',
          minWidth: 100,
          ellipsis: true
        },
        {
          title: '操作',
          width: 180,
          fixed: 'right',
          render: (h, data) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                domProps: {
                  innerHTML:
                    '<i class="ivu-icon ivu-icon-ios-nutrition-outline"></i> 修改'
                },
                style: {
                  margin: '0px 2px 0px 0px'
                },
                on: {
                  click: () => {
                    // 调用子组件方法
                    self.$refs.Model.modelShow(data.row, 'edit')
                  }
                }
              }),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  margin: '0px 2px'
                },
                domProps: {
                  innerHTML:
                    '<i class="ivu-icon ivu-icon-ios-trash-outline"></i> 删除'
                },
                on: {
                  click: async () => {
                    self.$Modal.confirm({
                      title: '删除吗？',
                      content: '<h2>确认删除？</h2>',
                      onOk: async () => {
                        let param = {
                          img_id: data.row.img_id
                        }
                        let result = await self.post(
                          `/admin/Img/imgDel`,
                          param
                        )
                        if (result.data.code !== 200) {
                          self.$Message.error(result.data.msg)
                        } else {
                          self.$Message.success({
                            content: '删除成功',
                            duration: 3
                          })
                          self.query()
                        }
                      }
                    })
                  }
                }
              })
            ])
          }
        }
      ],
      tableData: [],
      // 分页
      pageSize: 10,
      currentPage: 1,
      totalCount: 0
    }
  },
  methods: {
    async query () {
      this.loading = true
      // 格式化参数
      const resp = await this.post(
        `/admin/Img/imgList`,
        Object.assign(this.queryForm, {
          limit: this.pageSize,
          page: this.currentPage
        })
      )
      const datas = resp.data.data
      if (resp.data.code != 200) {
        this.$Message.error(resp.data.msg)
      } else {
        // 处理映射
        this.tableData = mapField(datas.list, this.columns)
        this.totalCount = datas.count
        this.loading = false
      }
    },
    async queryCateGory () {
      // 格式化参数
      const resp = await this.post(`/admin/CateGory/cateGoryList`, {
        get_all: true,
        category_type: 1
      })
      const datas = resp.data.data
      if (resp.data.code != 200) {
        this.$Message.error(resp.data.msg)
      } else {
        this.cateGory = datas.list
      }
    },
    setPage (page) {
      this.currentPage = page
      this.query()
    },
    setLimit (limit) {
      this.pageSize = limit
      this.query()
    },
    add () {
      this.$refs.Model.modelShow()
    },
    updateTime (date) {
      this.queryForm.create_time_start = date[0]
      this.queryForm.create_time_end = date[1]
    }
  },
  async beforeMount () {
    await this.queryCateGory()
    await this.query()
  }
}
</script>
